package cn.cloudtogo.server.mysql;

import cn.cloudtogo.common.model.DatasourceTypes;
import cn.cloudtogo.common.model.ExternalDatasourceDao;
import cn.cloudtogo.common.model.ExternalDatasourceModel;
import cn.cloudtogo.common.types.ObjectId;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author yaolianhua789@gmail.com
 **/
@Component
@Slf4j
public class ExternalDatasourceUUIDMigrator {

    private final ExternalDatasourceDao externalDatasourceDao;

    public ExternalDatasourceUUIDMigrator(ExternalDatasourceDao externalDatasourceDao) {
        this.externalDatasourceDao = externalDatasourceDao;
    }

    private boolean isJavaUUID(ExternalDatasourceModel model) {
        String uuid = model.getUuid();
        if (uuid.length() == 36 && uuid.contains("-")) {
            return true;
        }
        return uuid.length() == 32;
    }

    /**
     * 这个方法运行在{@link SpringJdbcTemplateContextRefresher#refresh()}之前,保证更新后的DB组件的jdbc上下文会被重新加载
     */
    public synchronized void migrate() {
        List<ExternalDatasourceModel> models = externalDatasourceDao.list()
                .stream()
                .filter(e -> Objects.equals(e.getType(), DatasourceTypes.Mysql))
                .filter(this::isJavaUUID)
                .collect(Collectors.toList());

        for (ExternalDatasourceModel mysqlModel : models) {

            String objectId = ObjectId.get().toHexString();
            externalDatasourceDao.replaceUuid(mysqlModel.getUuid(), objectId);

        }

        log.info("migrate java uuid success. size '{}'", models.size());
    }
}
